package com.school.controller;

import com.school.common.PageRequest;
import com.school.common.PageResult;
import com.school.common.Result;
import com.school.entity.Building;
import com.school.service.BuildingService;
import com.school.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 楼栋控制器
 */
@Slf4j
@RestController
@RequestMapping("/building")
public class BuildingController {
    
    @Autowired
    private BuildingService buildingService;
    
    /**
     * 添加楼栋
     */
    @PostMapping("/add")
    public Result<Long> add(@Validated @RequestBody Building building) {
        Long id = buildingService.add(building);
        return Result.success("添加成功", id);
    }
    
    /**
     * 更新楼栋
     */
    @PostMapping("/update")
    public Result<Void> update(@Validated @RequestBody Building building) {
        buildingService.update(building);
        return Result.success("更新成功");
    }
    
    /**
     * 删除楼栋
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        buildingService.delete(id);
        return Result.success("删除成功");
    }
    
    /**
     * 批量删除楼栋
     */
    @PostMapping("/batch-delete")
    public Result<Map<String, Object>> batchDelete(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的楼栋");
            }
            log.info("批量删除楼栋，数量: {}", ids.size());
            int count = buildingService.batchDelete(ids);
            Map<String, Object> result = new HashMap<>();
            result.put("count", count);
            return Result.success("批量删除成功，共删除 " + count + " 条数据", result);
        } catch (Exception e) {
            log.error("批量删除楼栋失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询楼栋
     */
    @GetMapping("/get/{id}")
    public Result<Building> getById(@PathVariable Long id) {
        Building building = buildingService.getById(id);
        return Result.success(building);
    }
    
    /**
     * 查询所有楼栋
     */
    @GetMapping("/all")
    public Result<List<Building>> getAllBuildings() {
        List<Building> buildings = buildingService.getAllBuildings();
        return Result.success(buildings);
    }
    
    /**
     * 分页查询楼栋列表
     */
    @GetMapping("/list")
    public Result<PageResult<Building>> getList(
            @RequestParam(required = false) String buildingName,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPageNum(pageNum);
        pageRequest.setPageSize(pageSize);
        
        PageResult<Building> pageResult = buildingService.getPageList(buildingName, pageRequest);
        return Result.success(pageResult);
    }
    
    /**
     * 获取楼栋统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        Map<String, Object> statistics = buildingService.getStatistics();
        return Result.success(statistics);
    }
    
    /**
     * 导出楼栋数据
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) {
        try {
            List<Building> buildings = buildingService.getAllBuildings();
            
            List<String> headers = Arrays.asList(
                    "楼栋名称", "楼层数", "宿舍总数", "容纳人数", "已入住", "入住率(%)", "主题颜色", "备注"
            );
            
            List<List<Object>> dataList = new ArrayList<>();
            for (Building building : buildings) {
                List<Object> row = Arrays.asList(
                        building.getBuildingName(),
                        building.getFloors(),
                        building.getTotalRooms(),
                        building.getCapacity(),
                        building.getOccupied(),
                        building.getOccupancyRate(),
                        building.getThemeColor(),
                        building.getRemark()
                );
                dataList.add(row);
            }
            
            String fileName = "楼栋列表_" + System.currentTimeMillis();
            ExcelUtils.exportExcel(response, fileName, "楼栋信息", headers, dataList);
        } catch (IOException e) {
            log.error("导出楼栋数据失败", e);
        }
    }
    
    /**
     * 下载导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            List<String> headers = Arrays.asList(
                    "楼栋名称", "楼层数", "宿舍总数", "容纳人数", "已入住", "主题颜色", "备注"
            );
            
            List<List<Object>> dataList = new ArrayList<>();
            dataList.add(Arrays.asList("A栋", 6, 48, 192, 180, "#409EFF", ""));
            dataList.add(Arrays.asList("B栋", 6, 48, 192, 175, "#67C23A", ""));
            
            String fileName = "楼栋导入模板";
            ExcelUtils.exportExcel(response, fileName, "楼栋信息", headers, dataList);
        } catch (IOException e) {
            log.error("下载模板失败", e);
        }
    }
}

